<?php
use Workerman\Worker;
use Workerman\Lib\Timer;
require_once '../Workerman/Autoloader.php';

/**
 * Worker作为http[容器监听处理请求
 */
$worker = new Worker('http://0.0.0.0:8080');

$worker->onMessage = function($connection,$data)
{
  var_dump($_GET,$_POST);
  $connection->send("hello");
};

Worker::runAll();

/**
 * Worker作为websocket容器监听处理websocket请求
 */

$worker = new Worker('tcp://0.0.0.0:8080');

$worker->onMessage = function($connection,$data)
{
    $connection->send("hello");
};

Worker::runAll();

/**
 * Worker作为udp容器监听处理udp请求
 *
 */

$worker = new Worker('udp://0.0.0.0:8080');

$worker->onMessage = function($connection,$data){
    $connection->send('hello');
};

/**
 * Worker监听unix domain套接字
 */

$worker = new Worker('unix:///tmp/my.sock');

$worker->onMessage = function($connection,$data){
    $connection->send("hello");
};

Worker::runAll();


/**
 * 不执行任何监听Worker容器,用来处理一些定时任务
 */

$task = new Worker();
$task->onWorkerStart = function ($task)
{
    //每2.5秒执行一次
    $time_interval = 2.5;
    $Timer::add($time_interval,function(){
       echo "task run\n";
    });
};

Worker::runAll();


/**
 * int Worker::$id
 * 当前worker进程的id编号，范围为0到$worker->count-1。

这个属性对于区分worker进程非常有用，例如1个worker实例有多个进程，开发者只想在其中一个进程中设置定时器，则可以通过识别进程编号id来做到这一点，比如只在该worker实例id编号为0的进程设置定时器（见范例）。

注意：
进程重启后id编号值是不变的。

进程编号id的分配是基于每个worker实例的。每个worker实例都从0开始给自己的进程编号，所以worker实例间进程编号会有重复，但是一个worker实例中的进程编号不会重复。例如下面的例子：
 */

//worker实例1 有4个进程,进程id编号将分为0、1、2、3
$worker1 = new Worker("tcp://0.0.0.0:8585");
//设置启动4个进程
$worker1->count = 4;
//每个进程启动后打印当前进程id编号,即$worker1->id
$worker1->onWorkerStart = function($worker1)
{
    echo "worker1->id={$worker1->id}\n"
};

//worker实例2有两个进程,进程id编号将分别为0、1
$worker2 = new Worker('tcp://0.0.0.0:8686');
//设置启动2个进程
$worker2->count = 2;
//第个进程启动后打印当前进程id编号及 $worker2->id
$worker2->onWorkerStart = function(){
    echo "worker2->id={$worker2->id}\n";
};

//运行worker
Worker::runAll();

/**
 * 一个worker实例有4个进程，只在id编号为0的进程上设置定时器。
 */
$worker = new Worker('tcp://0.0.0.0:888');
$worker->count = 4;
$worker->onWorkerStart = function($worker)
{
    //只在id编号为 0 的进程上设置定时器,其它1,2,3号进程不设置定时器
    if($worker->id ===0)
    {
        Timer::add(1,function (){
            echo "4个worker进程,只在0号进程设置定时器\n";
        });
    }
};

Worker::runAll();


/**
 *  属性connections
 * array Worker::$connections
 * 格式为array(id=>connection, id=>connection, ...)
 */

$wkr = new Worker('text://0.0.0.0:8888');

$wkr->onWorkerStart = function($wkr){
    //定时每5秒执行一次
    Timer::add(0.1,function ()use($wkr){
        //遍历当前进程所有客户端连接,发送当前服务器的时间
        foreach($wkr->connections as $id=>$connection)
        {
            $connection->send('id: '.$id . ':::' .md5(rand(1,10000000).time()));
        }
    });
};

Worker::runAll();
